<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * @property int $id 
 * @property int $g_id 
 * @property string $account 
 * @property int $type 
 * @property int $addtime 
 */
class GroupUser extends BaseModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'group_user';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'g_id' => 'integer', 'type' => 'integer', 'addtime' => 'integer'];

    /**
     * @param $appid
     * @param $g_id
     * @param array $accounts
     * @return array[]|string
     */
    public static function addGroup($appid, $g_id, array $accounts)
    {
        if (!Group::where(['appid'=>$appid,'id'=>$g_id])->first('id'))
            return '群组不存在或已解散';

        $success = [];
        $fail = [];
        foreach ($accounts as $account)
        {
            $user = self::where(['account'=>$account,'g_id'   =>$g_id])->first();
            // 已存在无需添加
            if($user){
                $success[] = $account;
            }else{
                $data = [
                    'g_id'    => $g_id,
                    'account' => $account,
                    'type'    => 0,
                    'addtime' => time()
                ];
                if (self::insert($data))
                {
                    $success[] = $account;
                }else{
                    $fail[] = $account;
                }
            }
        }

        return ['success'=>$success, 'fail'=>$fail];
    }

    /**
     *
     * @param $appid
     * @param $g_id
     * @return array
     */
    public static function getGroupUserAll($appid,$g_id)
    {
        if (!Group::where(['appid'=>$appid,'id'=>$g_id])->first('id'))
        {
            return '群组不存在或已解散';
        }

        $sql = "select a.account,b.fd from hyy_group_user a left join hyy_user_bind b on b.account=a.account and b.appid=? where a.g_id=?";

        return Db::select($sql, [$appid, $g_id]);
    }

    /**
     * 获取群成员
     * @param $appid
     * @param $array
     * @return array
     */
    public static function getGroupUser($appid,$array)
    {
        $page = $array['page'] ?? 1;
        $size = $array['size'] ?? self::$_p_size;
        $g_id = isset($array['g_id']) ? intval($array['g_id']) : 0;

        if ($g_id <= 0)
        {
            return 'g_id is null';
        }

        if (!Group::where(['appid'=>$appid,'id'=>$g_id])->first('id'))
        {
            return '群组不存在或已解散';
        }

        $where = [
            'g_id' => $g_id,
        ];

        $data = self::where($where)
            ->select(['g_id','account','type','addtime'])
            ->offset(self::p_offset($page,$size))
            ->limit(self::p_size($size))
            ->get();

        if ($data)
        {
            $data = $data->toArray();
            foreach ($data as &$val)
            {
                switch ($val['type'])
                {
                    case 1:
                        $val['type'] = '群主';
                        break;
                    case 0:
                        $val['type'] = '成员';
                        break;
                    case 2:
                        $val['type'] = '管理员';
                        break;
                }
            }
            return $data;
        }
        return [];

    }

    public static function updateRead($appid,$account,$g_id,$msg_id=0)
    {
        // 修改当前用户未读消息id
        // 获取当前用户走后一条消息的id

        if ($msg_id > 0)
        {
            self::where(['g_id'=>$g_id, 'account'=>$account])
                ->update(['last_ack_msgid'=>$msg_id]);
        }else{
            $msg = GroupMsg::where(['g_id'=>$g_id,'appid'=>$appid])->orderByDesc('id')->limit(1)->get('id');
            if ($msg)
            {
                self::where(['g_id'=>$g_id, 'account'=>$account])
                    ->update(['last_ack_msgid'=>$msg[0]->id]);

                return ['msg_id'=>$msg[0]->id];
            }
        }

        return '更新失败';
    }

    /**
     * 删除群成员
     *
     * 群主删除成员时删了自己（也就是自己主动退出群）
     * 如果群内没成员就解散群，有成员时会自动把去群转给最新加进来成员
     *
     * @param $appid
     * @param $g_id
     * @param $accounts
     * @return array[]|string
     */
    public static function delUser($appid, $g_id, $accounts)
    {
        $g_id = intval($g_id);

        if ($g_id <= 0)
        {
            return 'g_id is null';
        }

        $group = Group::where(['appid'=>$appid,'id'=>$g_id])->first(['id','account']);
        if (!$group)
        {
            return '群组不存在或已解散';
        }

        if (!is_array($accounts))
        {
            $accounts = json_decode($accounts, true);
        }

        $succ = [];
        $fail = [];
        $has_owen = $fail;

        Db::beginTransaction();
        try {
            foreach ($accounts as $account)
            {
                // 判断是否存在群主
                if ($group['account'] == $account)
                {
                    $has_owen = true;
                }

                $row = self::where(['g_id'=>$g_id, 'account'=>$account])->delete();
                if (intval($row) > 0){
                    $succ[] = $account;
                }else{
                    $fail[] = $account;
                }
            }

            // 存在群主 如果群内没成员就解散群，有成员时会自动把去群转给最新加进来成员
            if ($has_owen)
            {
                // 获取当前的群成员
                $gourp_user = self::where(['g_id'=>$g_id,'type'=>0])
                    ->orderBy('id')
                    ->limit(1)
                    ->get(['account','addtime'])
                    ->toArray();

                if ($gourp_user)
                {
                    $gourp_user = $gourp_user[0];
                    // 修改群成员在群的 群主
                    self::where(['account'=>$gourp_user['account'],'g_id'=>$g_id])
                        ->update(['type'=>1]);

                    // 修改群的群主
                    Group::where(['id'=>$g_id,'appid'=>$appid])
                        ->update(['account'=>$gourp_user['account']]);

                }else{

                    // 直接删除群
                    Group::where(['id'=>$g_id])->delete();
                    // 删除群消息记录
                    GroupMsg::where(['g_id'=>$g_id])->delete();

                }
            }

            Db::commit();

            return ['succ'=>$succ, 'fail'=>$fail];
        }catch (\Exception $exception)
        {
            Db::rollBack();
            return $exception->getMessage();
        }

    }



}